package handler

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"loginApp/internal/model"
)

// PostLogin 处理 POST /login
func PostLogin(c *gin.Context) {
	var req model.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, model.LoginResponse{
			Code: 1, Message: "请求参数不完整",
		})
		return
	}

	// 验证用户名密码
	for _, u := range model.ValidUsers {
		if u.Username == req.Username && u.Password == req.Password {
			// 生成简单 UUID 作为 token
			token := uuid.NewString()
			model.TokenStore.Lock()
			model.TokenStore.Data[token] = u.Role
			model.TokenStore.Unlock()

			c.JSON(http.StatusOK, model.LoginResponse{
				Code:    0,
				Message: "登录成功",
				Role:    u.Role,
				Token:   token,
			})
			return
		}
	}

	c.JSON(http.StatusUnauthorized, model.LoginResponse{
		Code: 1, Message: "用户名或密码错误",
	})
}

// GetAuthCheck 处理 GET /auth/check
func GetAuthCheck(c *gin.Context) {
	token := c.GetHeader("Authorization")
	if token == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"code": 1, "message": "缺少token"})
		return
	}

	model.TokenStore.RLock()
	role, ok := model.TokenStore.Data[token]
	model.TokenStore.RUnlock()
	if !ok {
		c.JSON(http.StatusUnauthorized, gin.H{"code": 1, "message": "无效token"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 0, "message": "已登录", "role": role})
}
